package com.sxh.user.Utils;

import com.sxh.user.exception.BaseException;
import com.sxh.user.model.UserInfo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    //密钥
    @Value("${jwt.secret-base64}")
    private String base64Secret;
    private SecretKey SECRET_KEY;
    //有效时长
    private static final long EXPIRATION_TIME = 12*60*60*1000L;
    @PostConstruct      //延迟初始化
    public void JwtUtil() {
        this.SECRET_KEY = createKeyFromBase64String(base64Secret);
    }
    private SecretKey createKeyFromBase64String(String base64Secret) {
        byte[] decodedKey = Base64.getDecoder().decode(base64Secret);
        return new SecretKeySpec(decodedKey, SignatureAlgorithm.HS256.getJcaName());
    }
    //生成JWT Token
    public String createToken(Long userId) {
        Map<String, Object> claimMap = new HashMap<>();
        if(userId != null){
            claimMap.put("userId", userId);
        }
        return Jwts.builder()
                .setClaims(claimMap)
//                .setSubject(userId)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
    //解析JWT Token
    public Long parseToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return (Long) claims.get("userId");
        } catch (ExpiredJwtException e) {
            throw new BaseException("token已过期");
        } catch (io.jsonwebtoken.security.SignatureException e) {
            throw new BaseException("无效签名");
        } catch (Exception e) {
            throw new BaseException("无效token");
        }
    }
    //验证令牌是否有效
    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            throw new BaseException("token已过期");
        } catch (SignatureException e) {
            throw new BaseException("无效签名");
        } catch (Exception e) {
            throw new BaseException("无效token");
        }
    }
}
